<template>
  <div class="editWedding">
    <h1>添加图片</h1>
    <el-alert v-show="albumData==''" title="你还没有添加图片哦!" type="info" style="margin-bottom: 20px;">
    </el-alert>
    <el-form ref="formline" class="box" :rules="rules" :model="formline" label-width="80px">
      <el-form-item label="主图:" label-width="130px">
        <template slot-scope="scope">
          <form class="banner_loade load">
            <el-button class="upload" type="primary ">
              上传
              <input class="file" type="file" name="file" @change="uploadImgs($event,1)">
            </el-button>
            <div class="loade_img main">
              <img class="img_auto " :src="imagesData" alt="" style="margin-right:0;">
              <i class="el-icon-error  icon" v-show="imagesData" @click="deleteMain"></i>
            </div>
          </form>
        </template>
      </el-form-item>

      <el-form-item label="相册:" label-width="130px">
        <form class="banner_loade" enctype="multipart/form-data">
          <el-button class="upload" type="primary">
            添加多张图片
            <input class="file" type="file" name="file" @change="uploadImgs($event)" multiple>
          </el-button>
          <span class="clear" @click="clear" v-if="albumData.length">一键清除</span>
          <span>一次只可上传9张图片(建议上传10M以内大小图片)</span>
          <div class="loade_img list">

            <div v-for="(item,index) in albumData" :key="index" style="position: relative;">
              <img class="img_auto " :src="item" alt="">
              <i class="el-icon-error icon" @click="deleteImg(index)"></i>
            </div>
            <span class="img-num">共<i>{{albumData.length}}</i>张图片</span>
          </div>
        </form>
      </el-form-item>
      <el-form-item label="基础套餐:" label-width="130px" prop="packages">
        <el-input placeholder="请填写数量" v-model="formline.packages" style="width: 200px;"></el-input>
        <span>张</span>
      </el-form-item>
      <el-form-item label="超出套餐的价格:" label-width="130px" prop="extra">
        <el-input placeholder="请填写价格" v-model="formline.extra" style="width: 200px;"></el-input>
        <span>元</span>
      </el-form-item>

      <el-form-item>
        <el-button type="button" @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveInfo(formline)">提交</el-button>
      </el-form-item>
      <!-- <el-form-item>
        <template>
          <a href="/user/test/xxxx.txt" download="文件名.txt">点击下载</a>
        </template>
      </el-form-item> -->
    </el-form>

  </div>
</template>

<script>
  export default {
    data() {
      return {
        imagesData: [],
        albumData: [],
        info: [],
        region: '',
        id: '',
        type: '',
        formline: {
          packages: '', // 免费选择照片的张数
          extra: '' // 超出张数额外的钱
        },
        options: [{
            value: '0',
            label: '旅拍相册'
          },
          {
            value: '1',
            label: '婚纱相册'
          },
          {
            value: '2',
            label: 'BB相册'
          }
        ],
        rules: {
          packages: [{
            required: true,
            message: '请输入免费照片数量',
            trigger: 'blur'
          }],
          extra: [{
            required: true,
            message: '请输入附加价格',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.id = this.$route.query.userid
      this.type = this.$route.query.type
      let param = {
        userid: this.id,
        type: this.type
      }
      this.api.get('/api/findphoto', param).then(res => {
        console.log(res.data, '9999')
        if (res.code == 200) {
          console.log(res.data)
          let album = res.data
          this.formline.extra = album.extra
          this.formline.packages = album.packages
          if (res.data) {
            this.imagesData = album.mainpicture
            if (album.images) {
              this.albumData = album.images
            }
          }
          for (let i = 0; i < this.options.length; i++) {
            if (this.options[i].value == album.type) {
              this.region = this.options[i].label
            }
          }
        }
      })
    },
    methods: {
      uploadImg(e) { // 添加主图
        let file = e.target.files[0]
        let param = new FormData()
        param.append('files', file, file.name)
        console.log(param)
        let config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
        console.log(param)
        this.api.post('/api/imgs', param).then(res => {
          console.log(res.data)
          console.log(this.imagesData)
          this.imagesData = res.data[0]
        })
      },

      blobToFile(dataurl, filename) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {
          type: mime
        });
      },

      uploadImgs(e, info) {
        let that = this;
        let imglist = e.target.files;
        if (imglist.length > 9) {
          that.$message({
            info: 'info',
            message: '一次只可上传9张图片！'
          })
        } else {
          if (info) {
            let formData = new FormData()
            let reader = new FileReader()
            let imgName = imglist[0]
            reader.readAsDataURL(imglist[0])
            that.imgPreview(imgName, 1)
          } else {
            for (let i = 0; i < imglist.length; i++) {
              let formData = new FormData()
              let reader = new FileReader()
              let imgName = imglist[i]
              reader.readAsDataURL(imglist[i])
              that.imgPreview(imgName)
            }
          }
        }


        console.log(e.target.files)

        // 判断图片大小
        // if (imgName.size / 1024 > 10000) {
        //   alert('图片过大不支持上传')
        // } else {

        // }
      },
      imgPreview(file, info) {
        let self = this
        // 判断是否支持FileReade
        if (!file || !window.FileReader) return
        // 创建一个reader
        var reader = new FileReader()
        // 将图片转成base64格式
        reader.readAsDataURL(file)
        // 读取成功后的回调
        reader.onloadend = function() {
          let result = this.result
          let img = new Image()
          img.src = result
          console.log('============未压缩图片===========')
          console.log(result.length)
          img.onload = function() {
            let data = self.compress(img)
            console.log(data.length)
            self.imgUrl = result
            var param = new FormData()
            let imgData = self.blobToFile(data, 'ig1')
            console.log(data)
            param.append('files', imgData)
            self.api.post('/api/imgs', param).then(res => {
              console.log(res)
              if (info) {
                self.imagesData = res.data[0]
              } else {
                console.log(self.a)
                self.albumData.push(res.data[0])
              }

            })
          }
        }
      },
      compress(img) {
        let canvas = document.createElement("canvas");
        let ctx = canvas.getContext("2d");
        let initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        canvas.width = width;
        canvas.height = height;
        // 铺底色
        ctx.fillStyle = "#fff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(img, 0, 0, width, height);

        //进行最小压缩
        let ndata = canvas.toDataURL("image/jpeg", 0.1);
        console.log("*******压缩后的图片大小*******");
        // console.log(ndata)
        console.log(ndata.length);
        return ndata;
      },
      clear() { //一键清除所有照片
        let that = this;
        if (that.albumData.length > 1) {
          that.albumData = ''
        }


      },
      cancel() {
        this.$router.go(-1)
      },
      deleteImg(index) {
        this.albumData.splice(index, 1)
      },
      deleteMain() { // 删除主图
        this.imagesData = ''
      },
      saveInfo(formline) {
        console.log(formline)
        this.$refs.formline.validate((valid) => {
          if (valid) {
            const _this = this
            let param = {
              images: _this.albumData,
              type: _this.type,
              mainpicture: _this.imagesData,
              userid: _this.id,
              packages: formline.packages,
              extra: formline.extra
            }
            _this.api.post('/api/addphoto', param).then(res => {
              console.log(res.data)
              if (res.data) {
                _this.$message({
                  type: 'success',
                  message: '保存成功！'
                })
                setTimeout(function() {
                  _this.$router.go(-1)
                }, 2000)
              }
            })
          }
        })
      }
    }
  }
</script>

<style scoped>
  .img-num {
    position: absolute;
    right: 0;
    bottom: -20px;
    display: inline-block;
  }

  .img-num i {
    font-weight: 700;
  }

  .select {
    position: absolute;
    left: 20%;
    top: 0;
  }

  .file {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 35px;
    line-height: 35px;
    text-align: center;
    opacity: 0;
  }

  .el-button {
    width: 100px;
  }

  .load {

    height: 120px;
  }

  .loade_img {
    background: url('./../../../static/img/push.jpg')no-repeat;
    background-size: 80px 80px;
    width: 80px;
    height: 80px;
    margin-top: 20px;
    position: relative;
    display: flex;
    flex-direction: row;
  }

  .clear {
    cursor: pointer;
    margin: 0 10px;
    background-color: #6ab86a;
    color: #ffffff;
    padding: 5px;
    border-radius: 10px;
  }

  .list {
    flex-wrap: wrap;
    width: 100%;
    height: 100%;
  }

  .img_auto {
    width: 80px;
    height: 80px;
	object-fit: cover;
    margin-right: 20px;
  }

  .main .icon {
    font-size: 25px;
    position: absolute;
    z-index: 100;
    top: -12px;
    right: -17px;
  }

  .icon {
    font-size: 25px;
    position: absolute;
    top: -8px;
    right: 4px;
    z-index: 100;
  }

  .upload {
    position: relative;
    width: 120px;
    height: 35px;
  }
</style>
